/* eslint-disable no-async-promise-executor */
import { loginApi, getInfo, getUserDetailById } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    // console.log(token)
    state.token = token
    // 本地存储token
    setToken(token)
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // user login
  // 接收从login.vue里传过来的表单信息
  // 创建一个pormise对象来执行请求数据的函数loginApi
  // 数据传入到'@/api/user'

  login({ commit }, userInfo) {
    // console.log(userInfo)
    // const { username, password } = userInfo
    return new Promise(async(resolve, reject) => {
      try {
        const res = await loginApi(userInfo)
        // console.log(res)
        // res里有data数据,是从后台传来的token
        commit('SET_TOKEN', res.data)
        resolve()
        // 调用从'@/utils/auth'中导入的setToken将token存入到cookie中
        // setToken(res.data)
      } catch (error) {
        reject(error)
      }

      // .then((response) => {
      //   console.log(response)
      //   const { data } = response

      //   commit('SET_TOKEN', data)
      //   setToken(data.token)
      //   resolve()
      // })
      // .catch((error) => {
      //   reject(error)
      // })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise(async(resolve, reject) => {
      const response = await getInfo(state.token)
      const res = await getUserDetailById(response.data.userId)
      // console.log(response)
      // console.log(res)
      commit('SET_NAME', res.data.username)
      // console.log(response.data.staffPhoto)
      commit('SET_AVATAR', res.data.staffPhoto)
      resolve(response.data)
      // .then((response) => {
      //   const { data } = response

      //   if (!data) {
      //     return reject('Verification failed, please Login again.')
      //   }

      //   const { name, avatar } = data

      //   commit('SET_NAME', name)
      //   commit('SET_AVATAR', avatar)
      //
      // })
      // .catch((error) => {
      //   reject(error)
      // })
    })
  },

  // user logout
  logout({ commit, state }) {
    removeToken() // must remove  token  first
    resetRouter()
    commit('RESET_STATE')
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
